﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using Cornerstone.Tools;
using dlCentral.Utils;
using dlCentral.PluginHandlers;

namespace dlCentral.Scrapper
{
    class TheMovieDB
    {
        #region API variables

        // NOTE: To other developers creating other applications, using this code as a base
        //       or as a reference. PLEASE get your own API key. Do not reuse the one listed here
        //       it is intended for download central use ONLY. API keys are free and easy to apply
        //       for. Visit this url: http://api.themoviedb.org/2.0/docs/

        private const string apiMovieUrl = "http://api.themoviedb.org/2.1/{0}/{1}/xml/85d41d579e6ae2f6f3f2d38598a6477c/";

        private static string apiMovieImdbLookup = string.Format(apiMovieUrl, "Movie.imdbLookup", "en");
        private static string apiMovieSearch = string.Format(apiMovieUrl, "Movie.search", "en");
        private static string apiMovieGetInfo = string.Format(apiMovieUrl, "Movie.getInfo", "en");
        private static string apiHashGetInfo = string.Format(apiMovieUrl, "Hash.getInfo", "en");

        #endregion

        public bool Search(ref MediaDetail m) {
            return Search(ref m  , null);
        }

        public bool Search(ref MediaDetail m, int? year) 
        {
            
            string url = apiMovieSearch + m.Title;
            if (year != null) url += "+" + year;

            XmlNodeList xml = getXML(url);
            if (xml == null)return false;

            XmlNodeList movieNodes = xml.Item(0).SelectNodes("//movie");
            if (!getMovieInformation(ref m, movieNodes[0])) return false;
            // try to grab posters from the xml results
            XmlNodeList posterNodes = xml.Item(0).SelectNodes("//image[@type='poster']");
            foreach (XmlNode posterNode in posterNodes)
            {
                if (posterNode.Attributes["size"].Value == "cover")
                {
                    m.Thumb = posterNode.Attributes["url"].Value;
                    return true;
                }
            }
            return false;
        }

 
        private bool getMovieInformation(ref MediaDetail m, XmlNode movieNode) {
            if (movieNode == null)
                return false;

            if (movieNode.ChildNodes.Count < 2 || movieNode.Name != "movie")
                return false;

            foreach (XmlNode node in movieNode.ChildNodes) {
                string value = node.InnerText;
                switch (node.Name) {
                    case "id":
                        m.MovieDBId = value;
                        break;
                    case "name":
                        m.Title = value;
                        break;
                    case "released":
                        DateTime date;
                        if (DateTime.TryParse(value, out date))
                            m.Year = date.Year;      
                        break;
                    case "imdb_id":
                        m.ImdbID = value;
                        break;
                    case "url":
                        m.DetailsURL = value;
                        break;
                    case "overview":
                        m.Plot = value;
                        break;
                    case "runtime":
                        int runtime = 0;
                        if (int.TryParse(value, out runtime))
                        m.Runtime = runtime;
                        break;
                    case "cast": // Actors, Directors and Writers
                        foreach (XmlNode person in node.ChildNodes) {
                            string name = person.Attributes["name"].Value;
                            string job = person.Attributes["job"].Value;
                            switch (job) {
                                case "Director":
                     //               movie.Directors.Add(name);
                                    break;
                                case "Actor":
                     //               movie.Actors.Add(name);
                                    break;
                                case "Screenplay":
                     //               movie.Writers.Add(name);
                                    break;
                            }
                        }
                        break;
                    case "categories":
                        foreach (XmlNode category in node.ChildNodes) {
                            string genre = category.Attributes["name"].Value;
                            string type = category.Attributes["type"].Value;
                            if (type == "genre") {
                       //         movie.Genres.Add(genre);
                            }
                        }
                        break;
                }
            }

            return true;
        }


 
 
        // given a url, retrieves the xml result set and returns the nodelist of Item objects
        private static XmlNodeList getXML(string url) {
            WebGrabber grabber = dlCentralUtils.GetWebGrabberInstance(url);
            grabber.Encoding = Encoding.UTF8;

            if (grabber.GetResponse())
                return grabber.GetXML("OpenSearchDescription");
            else
                return null;
        }
         
        
 


    }


    }

